<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <el-card>
        <el-form
          :rules="rules"
          :inline="true"
          ref="conncectFormRef"
          :model="connectForm"
          class="form-contain"
          size="small"
        >
          <el-form-item :label="t('robo.ip')" prop="ip">
            <el-input
              v-model="connectForm.ip"
              :disabled="roboClientStatus"
              :placeholder="t('robo.ip')"
              @keyup.enter="connect(conncectFormRef)"
            />
          </el-form-item>
          <el-form-item :label="t('robo.port')" prop="port">
            <el-input
              type="number"
              v-model.number="connectForm.port"
              :disabled="roboClientStatus"
              :placeholder="t('robo.port')"
              @keyup.enter="connect(conncectFormRef)"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              :type="roboClientStatus ? 'danger' : 'primary'"
              @click="connect(conncectFormRef)"
              :loading="loading"
            >
              {{ t(roboClientStatus ? 'robo.disconnect' : 'robo.connect') }}
            </el-button>
          </el-form-item>
        </el-form>

        <el-form
          ref="ruleFormRef"
          :model="roboForm"
          :rules="rules"
          :inline="true"
          class="demo-ruleForm"
          label-position="left"
          size="small"
        >
          <el-form-item :label="t('robo.handShake')" prop="handShake">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.handShake')"
              v-model="roboForm.handShake"
            />
          </el-form-item>

          <el-form-item :label="t('robo.srmNo')" prop="srmNo">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.srmNo')"
              v-model="roboForm.srmNo"
            />
          </el-form-item>

          <el-form-item :label="t('robo.palletType')" prop="palletType">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.palletType')"
              v-model="roboForm.palletType"
            />
          </el-form-item>

          <el-form-item :label="t('robo.taskNo')" prop="taskNo">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.taskNo')"
              v-model="roboForm.taskNo"
            />
          </el-form-item>

          <el-form-item :label="t('robo.sourcePosX')" prop="sourcePosX">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.sourcePosX')"
              v-model="roboForm.sourcePosX"
            />
          </el-form-item>

          <el-form-item :label="t('robo.sourcePosY')" prop="sourcePosY">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.sourcePosY')"
              v-model="roboForm.sourcePosY"
            />
          </el-form-item>

          <el-form-item :label="t('robo.sourcePosZ')" prop="sourcePosZ">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.sourcePosZ')"
              v-model="roboForm.sourcePosZ"
            />
          </el-form-item>

          <el-form-item
            :label="t('robo.destinationPosX')"
            prop="destinationPosX"
          >
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.destinationPosX')"
              v-model="roboForm.destinationPosX"
            />
          </el-form-item>

          <el-form-item
            :label="t('robo.destinationPosY')"
            prop="destinationPosY"
          >
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.destinationPosY')"
              v-model="roboForm.destinationPosY"
            />
          </el-form-item>

          <el-form-item
            :label="t('robo.destinationPosZ')"
            prop="destinationPosZ"
          >
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.destinationPosZ')"
              v-model="roboForm.destinationPosZ"
            />
          </el-form-item>

          <el-form-item :label="t('robo.command')" prop="command">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.command')"
              v-model="roboForm.command"
            />
          </el-form-item>

          <el-form-item :label="t('robo.emergencyStop')" prop="emergencyStop">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.emergencyStop')"
              v-model="roboForm.emergencyStop"
            />
          </el-form-item>

          <el-form-item :label="t('robo.alarmAck')" prop="alarmAck">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.alarmAck')"
              v-model="roboForm.alarmAck"
            />
          </el-form-item>

          <el-form-item :label="t('robo.taskCompeteAck')" prop="taskCompeteAck">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.taskCompeteAck')"
              v-model="roboForm.taskCompeteAck"
            />
          </el-form-item>

          <el-form-item
            :label="t('robo.taskVerification')"
            prop="taskVerification"
          >
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.taskVerification')"
              v-model="roboForm.taskVerification"
            />
          </el-form-item>

          <el-form-item :label="t('robo.standby')" prop="standby">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.standby')"
              v-model="roboForm.standby"
            />
          </el-form-item>

          <el-form-item :label="t('robo.stb')" prop="stb">
            <el-input
              type="number"
              :rows="18"
              :placeholder="t('robo.stb')"
              v-model="roboForm.stb"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
              :disabled="!roboClientStatus"
              :loading="loading"
            >
              {{ t('robo.send') }}
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">
              {{ t('robo.reset') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-col>
    <el-col :span="18">
      <Log />
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import {
  ElMessage,
  FormInstance,
  FormRules,
  TabsPaneContext,
} from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import Log from '@/components/Log/roboLog.vue'
import { closeClient, creatClient, sendMessageByClient } from '@/api/robo'
import { useI18n } from 'vue-i18n'
import { roboStore } from '@/store/roboStore'
import { storeToRefs } from 'pinia'
const { t } = useI18n()

const loading = ref(false)

const store = roboStore()
const ruleFormRef = ref<FormInstance>()

const roboForm = reactive({
  handShake: 0, // WCS 与SRM 握手信号,WCS 发送的脉冲信号,频率为 1HZ
  srmNo: 0, // SRM 编号
  /**
   * 托盘类型（可以替换货物高度类型：1，2，3。。。）
   */
  palletType: 0,
  /**
   * 任务号
   */
  taskNo: 0,
  /**
   * 源列(库口位置 801、802)
   */
  sourcePosX: 0,
  /**
   * 源层（库口位置 0）
   */
  sourcePosY: 0,
  /**
   * 源排（库口位置 0）
   */
  sourcePosZ: 0,
  /**
   * 目标列（库口位置 901、902）
   */
  destinationPosX: 0,
  /**
   * 目标层（库口位置 0）
   */
  destinationPosY: 0,
  /**
   * 目标排（库口位置 0）
   */
  destinationPosZ: 0,
  /**
   * 0= 无
   * 1= 入库
   * 2= 出库
   * 3= 移动
   * 4= 单取
   * 5= 单放
   * 6= 库内搬运
   * 9= 任务删除
   */
  command: 0,
  emergencyStop: 0, // 1= SRM 紧急停止
  alarmAck: 0, // 1= SRM 报警解除
  taskCompeteAck: 0, // 任务完成确认
  taskVerification: 0, // 任务校验，将上位机发过来的命令，以及原地址和目标地址总和
  standby: 0, // 备用
  stb: 0, // WCS 通讯位
})

// initWebSocket('simulator')
const { roboClientStatus, roboClientIp, roboClientPort } = storeToRefs(store) // 连接状态

// 连接信息表单
const connectForm = reactive({
  ip: roboClientIp.value,
  port: roboClientPort.value,
})

// 表单校验规则
const rules = reactive<FormRules>({
  ip: [{ required: true, message: '请填写IP地址', trigger: 'blur' }],
  port: [
    {
      required: true,
      message: '请填写连接端口',
      trigger: 'change',
    },
    { type: 'number', message: '端口号必须为数字类型' },
  ],
  message: [
    {
      required: true,
      message: '请填写报文',
      trigger: 'change',
    },
  ],
})

// 创建客户端
const conncectFormRef = ref<FormInstance>()
const connect = async (formEl: FormInstance | undefined) => {
  // 储存ip和port，解决刷新丢失
  store.setRoboClientIp(connectForm.ip)
  store.setRoboClientPort(connectForm.port)

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      if (roboClientStatus.value) {
        // 断开连接
        closeClient()
          .then((res) => {
            store.setRoboClientStatus(false)
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        // 建立连接
        creatClient(connectForm.ip, connectForm.port)
          .then((res) => {
            store.setRoboClientStatus(true)
          })
          .finally(() => {
            loading.value = false
          })
      }
    }
  })
}

// 发送消息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      sendMessageByClient(roboForm)
        .then((res) => {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'success',
            duration: 1000,
          })
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}

// 重置消息表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped lang="scss">
.form-contain {
  margin-bottom: 20px;
}
</style>
